package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeException;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常捕获
 *
 * @author DuGuanghan
 * @since 2024-01-08 16:02:10
 */
@Slf4j
@ResponseBody
@ControllerAdvice(value = "com.atguigu.gulimall.product.app")
public class GulimallExceptionControllerAdvice {

    /**
     * 捕获数据校验异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验信息出错：{},错误类型：{}", e.getMessage(), e.getClass());

        BindingResult result = e.getBindingResult();
        Map<String, String> map = new HashMap<>();

        // 遍历所有的异常信息
        result.getFieldErrors().forEach((item) -> {
            map.put(
                    // 获取错误信息
                    item.getField(),
                    // 获取错误的字段
                    item.getDefaultMessage()
            );
        });

        return R.error(BizCodeException.VALID_EXCEPTION.getCode(),
                BizCodeException.VALID_EXCEPTION.getMsg()).put("data", map);
    }

    /**
     * 捕获其他异常
     */
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable e) {
        log.error("错误信息：", e);

        return R.error(BizCodeException.UNKNOW_EXCEPTION.getCode(),
                BizCodeException.UNKNOW_EXCEPTION.getMsg());
    }
}
